import Component from '@glimmer/component';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { service } from '@ember/service';

export default class LoginComponent extends Component {
  @service api;
  @service message;

  @tracked userKey = '';
  @tracked isLoading = false;
  @tracked errorMessage = '';

  @action
  updateUserKey(event) {
    this.userKey = event.target.value;
    this.errorMessage = ''; // 清除错误信息
  }

  @action
  async handleLogin(event) {
    event.preventDefault();
    
    if (!this.userKey.trim()) {
      this.errorMessage = '请输入用户key';
      return;
    }

    this.isLoading = true;
    this.errorMessage = '';

    try {
      const response = await this.api.loginByUserKey(this.userKey.trim());
      
      if (response.success) {
        this.message.success('登录成功');
        // 登录成功后，通过父组件切换显示内容
        if (this.args.onLoginSuccess) {
          this.args.onLoginSuccess();
        }
      } else {
        if (response.code === 300) {
          this.errorMessage = '用户未登录或用户key无效';
        } else {
          this.errorMessage = response.message || '登录失败，请重试';
        }
      }
    } catch (error) {
      console.error('登录请求失败:', error);
      this.errorMessage = '网络错误，请检查连接后重试';
    } finally {
      this.isLoading = false;
    }
  }
}